
package com.example.function.project.service.impl;

import com.example.common.page.CP_Page;
import com.example.common.page.CP_Sorter;
import com.example.common.support.CustomException;
import com.example.common.support.CustomExceptionType;
import com.example.common.util.CP_DownloadFileUtil;
import com.example.config.FileConfig;
import com.example.function.project.dao.one.ProspectusTemplateJpaRepository;
import com.example.function.project.model.one.ProspectusTemplate;
import com.example.function.project.service.IProspectusTemplateService;
import com.example.function.sys.service.ISysUserService;
import com.example.support.OssResult;
import com.example.support.OssTemplate;
import com.github.wenhao.jpa.Specifications;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


/**
 * Description: <prospectusTemplateServiceImpl>. <br>
 * <p>
 * <prospectusTemplateservice实现类>
 * </p>
 * generate time:2021-7-30 16:24:12
 *
 * @author hanqf
 * @version V1.0
 */
@Service(value="prospectusTemplateService")
@Slf4j
@CacheConfig(cacheNames = "commonCache")
@Transactional
public class ProspectusTemplateServiceImpl implements
		IProspectusTemplateService {

    @Autowired
    ProspectusTemplateJpaRepository prospectusTemplateJpaRepository;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private OssTemplate ossTemplate;

	@SuppressWarnings("unchecked")
	@Override
	public Page<ProspectusTemplate> findByPage(CP_Page page, CP_Sorter sorter, ProspectusTemplate prospectusTemplate,String... fields) {
		log.info("分页查询ProspectusTemplate列表begin");
		log.info("ProspectusTemplateServiceImpl findByPage begin");

		if (sorter == null) {
			sorter = new CP_Sorter();
		}
        //排序
		Sort sort = Sort.by(sorter.getSortType().equals(CP_Sorter.DESC) ? Sort.Direction.DESC : Sort.Direction.ASC, sorter.getSortName());
        //分页
        Pageable pageable = PageRequest.of(page.getIndex(), page.getPageSize(), sort);

		Specification<ProspectusTemplate> specification = Specifications.<ProspectusTemplate>and()
				.eq(prospectusTemplate.getId()!=null,"id",prospectusTemplate.getId())
				.build();



        Page<ProspectusTemplate> resultPage = prospectusTemplateJpaRepository.findAll(specification, pageable);

       // page.setTotal(resultPage.getTotalElements());

        //如有需要，可以转成list
        //List<ProspectusTemplate> results = resultPage.getContent();



		log.info("分页查询ProspectusTemplate列表end");
		log.info("ProspectusTemplateServiceImpl findByPage end");
		return resultPage;
	}

	@Override
	@CacheEvict(allEntries = true, beforeInvocation = true)
	public ProspectusTemplate update(ProspectusTemplate prospectusTemplate){
		log.info("ProspectusTemplateServiceImpl update begin");
        prospectusTemplateJpaRepository.save(prospectusTemplate);
		log.info("ProspectusTemplateServiceImpl update end");
	return prospectusTemplate;
	}
	@Override
	@CacheEvict(allEntries = true, beforeInvocation = true)
	public ProspectusTemplate add(ProspectusTemplate prospectusTemplate){
		log.info("ProspectusTemplateServiceImpl add begin");
        prospectusTemplateJpaRepository.save(prospectusTemplate);
		log.info("ProspectusTemplateServiceImpl add begin");
		return prospectusTemplate;
	}

	@Override
	@Cacheable(key = "#id+''+#fields+'ProspectusTemplateServiceImpl.findById'")
	public ProspectusTemplate findById(java.lang.Long id ,String... fields) {
		log.info("ProspectusTemplateServiceImpl findById begin");
        ProspectusTemplate prospectusTemplate = prospectusTemplateJpaRepository.findByIdNew(id);
		prospectusTemplateJpaRepository.lazyInitialize(prospectusTemplate,fields);
		log.info("ProspectusTemplateServiceImpl findById end");
		return prospectusTemplate;
	}
	@Override
	@CacheEvict(allEntries = true, beforeInvocation = true)
	public void delete(java.lang.Long... ids) {
		log.info("ProspectusTemplateServiceImpl delete begin");
		if (ArrayUtils.isEmpty(ids)){
			return;
		}
		//(Object[])ids 是为了避免编译警告：最后一个参数使用了不准确的变量类型的 varargs 方法的非 varargs 调用
		Specification<ProspectusTemplate> specification = Specifications.<ProspectusTemplate>and()
				.in("id", (Object[])ids)
				.build();

		List<ProspectusTemplate> results = prospectusTemplateJpaRepository.findAll(specification);


        // 删除记录
        prospectusTemplateJpaRepository.deleteAll(results);


		//删除文件
		for (ProspectusTemplate file : results) {
			ossTemplate.deleteFile(file.getTemplateSaveName());
		}


		log.info("ProspectusTemplateServiceImpl delete end");
	}

	@Override
	@Cacheable(key = "'ProspectusTemplateServiceImpl.findAll'")
	public List<ProspectusTemplate> findAll() {
		return prospectusTemplateJpaRepository.findAll();
	}


	@Override
	public void downLoadFile(Long fileId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		final ProspectusTemplate prospectusTemplate = findById(fileId);
		if (prospectusTemplate != null) {
			CP_DownloadFileUtil.builder()
					.fileName(prospectusTemplate.getTemplateName())
					.fileSize(prospectusTemplate.getTemplateSize().intValue())
					.inputStream(ossTemplate.getInputStream(prospectusTemplate.getTemplateSaveName()))
					.build().download(response);
		}
	}

	@Override
	public int uploadFiles(MultipartFile[] multipartFiles) {
		log.info("ProspectusTemplateServiceImpl updateFiles end");

		for (MultipartFile multipartFile : multipartFiles) {

			String fileName = multipartFile.getOriginalFilename();
			String suffix = "";

			String saveFileName = "ProjecPtrospectusFiles/" + UUID.randomUUID();
			if (fileName.contains(".")) {
				suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				saveFileName = saveFileName + "." + suffix;
			}else {
				throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "文件没有后缀不能上传");
			}

			//文件后缀有效性验证
			if (!FileConfig.isSuffixesOK(suffix)) {
				throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "文件后缀不符合要求，允许的文件后缀【"+FileConfig.ALLOW_FILE_SUFFIXES+"】");
			}

			final OssResult ossResult = ossTemplate.uploadFile(multipartFile, saveFileName);
			if (ossResult.isSuccess()) {
				ProspectusTemplate file = new ProspectusTemplate();
				file.setTemplateName(multipartFile.getOriginalFilename());
				file.setTemplateSaveName(saveFileName);
				file.setTemplateSize(multipartFile.getSize());
				add(file);
			} else {
				throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "文件上传失败", ossResult.getMsg());
			}
		}

		log.info("ProspectusTemplateServiceImpl updateFiles end");
		return multipartFiles.length;
	}
}
